"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : DMS分布式锁
Case Name   : 备机故障恢复，主机持有X锁
Create At   : 2023/4/20
Owner       : opentestcase033
Description :
    1.创建测试表
    2.主节点开启事务A执行drop table，不提交
    3.备节点重启
    4.在备节点进行select，主节点清空表
    5.清理环境
Expect:
    1.成功
    2.成功，获取X锁
    3.成功
    4.成功，truncate阻塞
    5.成功
History     :
"""

import os
import time
import unittest

from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 > Primary_SH.get_node_num(), '非1+2以上环境不执行')
class DmsOck(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.std_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.table = 't_dms_ock_0070'

    def test_dms_ock(self):
        text1 = '-----step1:创建测试表;expect:执行成功-----'
        self.log.info(text1)
        create_tb = f"drop table if exists {self.table} cascade;" \
                    f"create table {self.table}(" \
                    f"id int, name varchar, source number) with(segment=on);" \
                    f"insert into {self.table} values (1,'haha',92)"
        create_res = self.pri_sh.execut_db_sql(create_tb)
        self.log.info(create_res)
        self.assertTrue(self.constant.CREATE_TABLE_SUCCESS in create_res
                        and self.constant.INSERT_SUCCESS_MSG in create_res,
                        f"执行失败:{text1}")

        text2 = '-----step2:主节点开启事务A执行drop table，不提交;expect:成功-----'
        self.log.info(text2)
        sql_a = f'''begin;
        drop table {self.table};
        select pg_sleep(70);'''
        session = ComThread(self.pri_sh.execut_db_sql, args=(sql_a,))
        session.setDaemon(True)
        session.start()
        time.sleep(2)

        text3 = '-----step3:备节点重启;expect:成功-----'
        self.log.info(text3)
        stop_res = self.std_sh.exec_cm_ctl('stop', '-n 2')
        self.log.info(stop_res)
        self.assertIn(self.constant.cm_stop_node_success_msg, stop_res,
                      f"执行失败:{text3}")
        start_res = self.std_sh.exec_cm_ctl('start', '-n 2')
        self.log.info(start_res)
        self.assertIn(self.constant.cm_start_node_success_msg, start_res,
                      f"执行失败:{text3}")
        time.sleep(20)
        status = self.std_sh.exec_cm_ctl('query', '-Cvw')
        self.log.info(status)
        self.assertNotIn('Unavailable', status, f'集群状态异常:{text3}')
        session.join(70)
        res = session.get_result()
        self.log.info(f'session_results: {res}')
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, res, f"执行失败:{text2}")

        text4 = '-----step4:在备节点进行select，主节点清空表;expect:成功，truncate阻塞-----'
        self.log.info(text4)
        sql = f"start transaction;" \
              f"select * from {self.table};" \
              f"select pg_sleep(10);"
        session1 = ComThread(self.std_sh.execut_db_sql, args=(sql,))
        session1.setDaemon(True)
        session1.start()
        time.sleep(1)
        session2 = ComThread(self.pri_sh.execut_db_sql,
                             args=(f"truncate table {self.table};",))
        session2.setDaemon(True)
        session2.start()
        session2.join(4)
        session1.join(10)
        res_a = session1.get_result()
        self.log.info(f'session1_results: {res_a}')
        res_b = session2.get_result()
        self.log.info(f'session2_results: {res_b}')
        self.assertIn('1 | haha |     92', res_a, f"执行失败{text4}")
        self.assertIsNone(res_b, f"执行失败{text4}")

    def tearDown(self):
        text5 = '-----step5:清理环境 expect:成功-----'
        self.log.info(text5)
        drop_tb_res = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.table} cascade;")
        self.log.info(drop_tb_res)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS,
                      drop_tb_res, f"删表失败:{text5}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
